#include "base_array.h"

#include "base_memory.h"


//-----------------------------------------------------------------------------
// Dynamic array
//-----------------------------------------------------------------------------


typedef struct
{
    int size;
    int sizePerElem;
    int padA;
    int padB;
} _Array;

#define _FROM_ARRAY(a)  (((_Array*)(a))-1)
#define _TO_ARRAY(a)    (void*)(a+1)

void* array_new(int size, int sizePerElem)//Create a new array.(tableau)
{
    if(size < 0 || sizePerElem < 1) { return 0; }

    _Array *a = mem_allocate(sizeof(_Array) + size*sizePerElem);
    a->size         = size;
    a->sizePerElem  = sizePerElem;
    return _TO_ARRAY(a);
}

void array_delete(void *array) // free
{
    if(array == 0) { return; }

    _Array *a = _FROM_ARRAY(array);
    mem_free(a);
    return;
}

void* array_resize(void *array, int newSize) //Resize an array.
{
    if(array == 0 || newSize < 0) { return 0; }

    _Array *a = _FROM_ARRAY(array);
    void *b = array_new(newSize, a->sizePerElem);

    int nbBytes = (newSize > a->size ?  a->size : newSize) * a->sizePerElem;
    memcpy(b, array, nbBytes);

    array_delete(array);;
    return b;
}

int array_size(void *array)//Get size of an array
{
    if(array == 0) { return 0; }

    _Array *a = _FROM_ARRAY(array);
    return a->size;
}
